﻿#ifndef SPTESTADAPTOR_H
#define SPTESTADAPTOR_H

#include "sptestadaptor_global.h"
#include "lfsapi.h"
#include <QThread>
#include <dbus/dbus.h>
#include <sstream>
using namespace std;

class QVariant;
class QMutex;
class QWaitCondition;
class QMessageBox;

class SPTESTADAPTORSHARED_EXPORT SPTestAdaptor
        : public QThread
{
    Q_OBJECT

public:
    SPTestAdaptor();
    virtual ~SPTestAdaptor();

signals:
    void sendMessage(const char* msg, qint64 param1, qint64 param2);
    void doActionConfirm(const QString& title, const QString& text, const QString& detailedText);

public slots:
    int Open(QVariant &logicalName, QVariant& timeout, QVariant& LFSResult);
    int Register(QVariant& timeout, QVariant& LFSResult);
    int Deregister(QVariant& timeout, QVariant& LFSResult);
    int Close(QVariant& timeout, QVariant& LFSResult);
    int ActionConfirm(QVariant& timeout, QVariant& title, QVariant& text, QVariant& detailedText);

protected:
    void generateDBusObjectName();
    void releaseDBusObjectName();
    void startDBusListener();
    void run() override;
    bool waitForResult(LPLFSRESULT* ppResult, unsigned long time = ULONG_MAX);
    void FreeResult(LPLFSRESULT pResult);

    HSERVICE m_hService;
    char m_szDBusObjectName[64];

private slots:
    void on_message(const char* msg, qint64 param1, qint64 param2);
    void on_actionPerform(const QString& title, const QString& text, const QString& detailedText);

private:
    void on_cmdComplete(qint64 msg_id, qint64 pointer);
    void on_infoGot(qint64 pointer);
    void on_executed(qint64 pointer);
    void on_eventArrived(qint64 event_id, qint64 pointer);

    void eventCallBack(int64_t msg_id, int64_t pointer);

    bool parseParam(DBusMessage* msg, qint64* param1, qint64* param2);

    static QMap<QString, int> g_refCounter;
    volatile bool m_isStarted;

    QMutex* m_mutex;
    QWaitCondition* m_waitCondition;

    LPLFSRESULT m_pLFSResult;
    bool m_isWaitTimeout;

    QMessageBox* m_actionConfirmMsgBox;
};

void TrimSpace(char* str);
void ParseExtraInfo(std::stringstream& ss, LPSTR lpszExtra);

#define DECLARE_STRINGSTREAM stringstream ss	//声明一个字符串流
#define BEGIN_GROUP ss << "{"	//开始组
#define BEGIN_GROUP_WITH_NAME(name) ss << name << ":" << "{"	//开始命名组
#define OUTPUT_NAME_VALUE(name, value) ss << name << ":" << value << ";"	//输出名称/值字段
#define OUTPUT_VALUE(value) ss << value << ";"		//输出值字段
#define END_GROUP ss << "};"	//结束组
#define GET_STRINGSTREAM_DATA(szData) szData = QString::fromUtf8(ss.str().c_str())		//取字符串流的数据
#define PARSE_EXTRAINFO(lpszExtra) ParseExtraInfo(ss, lpszExtra)	//解析Wosa返回信息结构体中的Extra数据

#endif // SPTESTADAPTOR_H
